<?php


namespace app\api\controller;


use app\common\lib\Show;
use think\Exception;
use think\facade\Cache;

class Cart extends Auth
{
    //购物车
    public function add()
    {
        if (!request()->isPost()) {
            return Show::error();
        }

        $id = input('id', 0, 'intval');
        $num = input('num', 0, 'intval');

        $data = [
            'id' => $id,
            'num' => $num,
        ];

        try {
            validate(\app\api\validate\Cart::class)->check($data);
        } catch (Exception $e) {
            return Show::error($e->getMessage());
        }

        $res = (new \app\common\business\Cart())->insertRedis($this->user_id, $id, $num);

        //大写的false,因为redis错误的时候返回的就是大写的FALSE
        if ($res === FALSE) {
            return Show::error();
        }

        return Show::success();
    }

    public function lists()
    {
        $ids = input('id', 0, 'trim');

        $data = (new \app\common\business\Cart())->lists($this->user_id, $ids);
        if (!$data) {
            return Show::error();
        }

        return Show::success($data);
    }

    public function delete()
    {
        if (!request()->isPost()) {
            return Show::error();
        }

        $id = input('id', 0, 'intval');
        $res = (new \app\common\business\Cart())->del($this->user_id, $id);

        if ($res === FALSE) {
            return Show::error();
        }

        return Show::success();
    }

    public function update()
    {
        if (!request()->isPost()) {
            return Show::error();
        }

        $id = input('id', 0, 'intval');
        $num = input('num', 0, 'intval');

        try {
            $res = (new \app\common\business\Cart())->update($this->user_id, $id, $num);
        } catch (Exception $e) {
            return Show::error([], $e->getMessage());
        }

        if (!$res) {
            return Show::error();
        }

        return Show::success();
    }
}